package edu.byui.chat;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SetData {
	private Connection con;
	private String url;

	public SetData() {
		url = "jdbc:mysql://localhost:3306/cit310";
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		}
		catch(Exception e) {
			System.out.println("You Had some other error, not a database error");
			e.printStackTrace();
		}
	}

	public void readMessage(String username, int num) {
		try {
			con = DriverManager.getConnection(url, "javadbc", "cit310");
			PreparedStatement readSQL = con.prepareStatement("UPDATE message SET message_read = 1 WHERE message_id = ? AND message_to = ?;");
			readSQL.setInt(1, num);
			readSQL.setString(2, username);
			readSQL.executeUpdate();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void checkUsernames(Message message) {
		try {
			con = DriverManager.getConnection(url, "javadbc", "cit310");
			PreparedStatement checkUsername = con.prepareStatement("SELECT (SELECT COUNT(*) FROM user WHERE user_name = ?), (SELECT COUNT(*) FROM user WHERE user_name = ?) FROM dual;");
			checkUsername.setString(1, (String)message.getFrom());
			checkUsername.setString(2, message.getTo());
			ResultSet temp = checkUsername.executeQuery();
			int count = 0;
			while(temp.next()) {
				count ++;
				if (temp.getInt(1) == 0) {
					PreparedStatement insertUsername = con.prepareStatement("INSERT INTO user VALUES(?);");
					insertUsername.setString(1, message.getFrom());
					insertUsername.executeUpdate();
				}
				if (temp.getInt(2) == 0) {
					PreparedStatement insertUsername = con.prepareStatement("INSERT INTO user VALUES(?);");
					insertUsername.setString(1, message.getTo());
					insertUsername.executeUpdate();
				}
			}
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void addMessage(Message message) {
		try {
			con = DriverManager.getConnection(url, "javadbc", "cit310");

			this.checkUsernames(message);
			String prepStatement = "INSERT INTO message VALUES(null, ?, ?, ?, ?, 0);";
			PreparedStatement updateData = con.prepareStatement(prepStatement);

			updateData.setString(1, message.getTo());
			updateData.setString(2, message.getFrom());
			updateData.setString(3, MySQLConversion.gregorToDateTime(message.getSent()));
			updateData.setString(4, message.getMessage());
			updateData.executeUpdate();
			con.close();

		}
		catch(SQLException e) {
			System.out.println("You had a database Error");
			e.printStackTrace();
		}
		catch(Exception e) {
			System.out.println("you Had some other error, not a database error");
			e.printStackTrace();
		}
	}
}
